const chalk = require('chalk');
const fs = require('fs');
const { promisify } = require('util');
const ora = require('ora');
const { exec } =require('child_process');
const promptList = require('./promptList');

function isExistFolder(file){
  fs.existsSync(file);
}


function loading(fn,message){
  return async (...args)=>{
    const spinner = ora(message);
    spinner.start();
    const data = await fn(...args);
    spinner.succeed();
    return data;
  }
}

function downloadGit(answer){
  const gitUrl = {
    ts:'https://github.com/devin-qu/demo-cli.git',  //ts模板对应的仓库路径
    js:'https://github.com/devin-qu/demo-cli.git' //js模板对应的仓库路径
  }
  exec(`git clone ${gitUrl[answer.type]} ${answer.projectName}`,(err)=>{
    if(err){
      console.log(chalk.red('初始化出错啦'))
      process.exit()//退出当前操作
    }else{
      console.log(chalk.red('初始化完成'))
      process.exit()//退出当前操作
    }
 })
}


function download(repo){
  return promisify(downloadGit)(repo);
}

function read(answer){
  if(answer.projectName &&answer.version ){
    let nowPath = process.cwd()
    fs.readFile(`${nowPath}/package.json`,(error,data)=>{
      if(error){
        console.log(chalk.red("读取文件错误"));
        process.exit()
      }else{
        //读取的data为buffer,需要转成js对象
        data=JSON.parse(data.toString())
        //拿到对象之后进行定制化修改
        data.name=answer.projectName
        data.version=answer.version
        //修改完成之后重写package.json文件
        fs.writeFile(`${nowPath}/package.json`,JSON.stringify(data,'',4),(error)=>{
          if(error){
            console.log(chalk.red('重写出错啦'))
          }else{
            console.log(chalk.red(`已将项目名称修改为${answer.projectName}`))
            console.log(chalk.red(`已将项目版本号修改为${answer.version}`))
          }
        })
      }
    })
  }
}


async function init(args) {
  const folderName = args[0];
  const folderPath = path.resolve(process.cwd(),folderName);
  const state = isExistFolder(folderPath);
  if (!state) {
    const answers = await promptList()
    await loading(download,'模板下载中...')(answers)
    await loading(read,'修改数据中...')(answers)
  }else{
    console.error('当前目录下已存在', folderName);
  }

  
}

module.exports = { init }
